//
//  LHPlayViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/7/21.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit

class LHPlayViewController: UIViewController,BMKMapViewDelegate {
    
    @IBOutlet weak var progressLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var mapView: UIView!
    @IBOutlet weak var playButton: UIButton!
    @IBOutlet weak var progressSlider: UISlider!
    @IBOutlet weak var speedSlider: UISlider!
    
    var baiduMapView:BMKMapView?
    var aMapView:MAMapView?
    
    let lhplayViewControllerForAMap = LHPlayViewControllerForAMap()
    
    var dataArray:NSArray?
    var timer:Timer?
    
    var index = 0
    
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        //屏幕常亮
        UIApplication.shared.isIdleTimerDisabled = true
        
        baiduMapView?.delegate = self
        
        aMapView?.delegate = lhplayViewControllerForAMap
        
        startTimer()
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        //屏幕常亮
        UIApplication.shared.isIdleTimerDisabled = false
        
        baiduMapView?.delegate = nil
        
        aMapView?.delegate = nil
        
        stopTimer()
        
        
    }
    
    deinit {
        
        stopTimer()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        stopTimer()
        
    }
    
    // MARK: - 开启定时器
    func startTimer() {
        
        if playButton.isSelected {
            
            timer = nil
            
            locationHistoryPlay()
            
        }
        
        
    }
    
    // MARK: - 关闭定时器
    func stopTimer() {
        
        if timer != nil {
            
            timer?.invalidate()
            
            timer = nil
            
        }
        
    }
    
    
    // MARK: - 初始化
    func setUpView() {
        
        // MARK: 初始化LHPlayViewControllerForAMap
        setUpLHPlayViewControllerForAMap()
        
        // MARK: speedSlider
        speedSlider.addTarget(self, action: #selector(stopTimer), for: .touchDown)
        speedSlider.addTarget(self, action: #selector(startTimer), for: .touchUpInside)
        
        // MARK: progressSlider
        progressSlider.addTarget(self, action: #selector(stopTimer), for: .touchDown)
        progressSlider.addTarget(self, action: #selector(startTimer), for: .touchUpInside)
        progressSlider.addTarget(self, action: #selector(progressSliderChangeIndex), for: .touchUpInside)
        
        if dataArray != nil {
            
            if (dataArray?.count)! > 0 {
                
                progressSlider.maximumValue = Float((dataArray?.count)! - 1)
                
            }
            
        }
        
        // MARK: 标题
        self.title = NSLocalizedString(LOCALIZABLE_STRING_LOCATION_HISTORY, comment: "")
        
        // MARK: 下面两个label
        progressLabel.text = NSLocalizedString(LOCALIZABLE_STRING_PROGRESS, comment: "")
        speedLabel.text = NSLocalizedString(LOCALIZABLE_STRING_SPEED, comment: "")
        
        // MARK: 用哪个地图
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            baiduMapView = BMKMapView.init(frame: self.mapView.bounds)
            
            //约束弊端,不同机型适配宽高
            baiduMapView?.height = STATIC_VALUE_SCREEN_HEIGHT - (self.navigationController?.navigationBar.height)! - 100
            baiduMapView?.width = STATIC_VALUE_SCREEN_WIDTH
            
            
            baiduMapView?.showMapScaleBar = true
            
            baiduMapView?.zoomLevel = 15
            
            
            //移动地图
            let c = getFirstPoint()
            
            if c != nil {
                
                let cc = coorForWGS84ToBd09(coor: c!)
                
                baiduMapView?.setCenter(cc, animated: false)
                
            }
            
            
            self.mapView.addSubview(baiduMapView!)
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP{
            
            ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
            AMapServices.shared().enableHTTPS = true
            
            ///初始化地图
            aMapView = MAMapView.init(frame: self.mapView.bounds)
            
            //约束弊端,不同机型适配宽高
            aMapView?.height = STATIC_VALUE_SCREEN_HEIGHT - 100
            aMapView?.width = STATIC_VALUE_SCREEN_WIDTH
            
    
            aMapView?.showsScale = true
            
            aMapView?.zoomLevel = 15
            
            
            //移动地图
            let c = getFirstPoint()
            
            if c != nil {
                
                let cc = AMapCoordinateConvert(c! , .GPS)
                
                aMapView?.setCenter(cc, animated: false)
                
            }
            
            
            
            ///把地图添加至view
            self.mapView.addSubview(aMapView!)
            
        }
        
    }
    
    // MARK: - progressSlider 改变index
    func progressSliderChangeIndex() {
        
        index = Int(progressSlider.value)
        
        drawLongLine()
        
    }
    
    // MARK: - 获取第一个点
    func getFirstPoint() -> CLLocationCoordinate2D? {
        
        if dataArray != nil {
            
            if (dataArray?.count)! > 0 {
                
                let h = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[0])
                
                let c = CLLocationCoordinate2DMake((h?.Lat?.doubleValue)!, (h?.Lng?.doubleValue)!)
                
                return c
                
            }
            
        }
        
        return nil
        
    }

    // MARK: - 开始,暂停
    @IBAction func touchPlayButton(_ sender: Any) {
        
        if !playButton.isSelected {
            
            if dataArray != nil {
                
                if (dataArray?.count)! > 0 {

                    locationHistoryPlay()
                    
                    playButton.isSelected = true
                    
                }
                
            }
            
        }else {
            
            playButton.isSelected = false
            
            stopTimer()
            
        }
        

    }
    
    // MARK: - 运行轨迹
    func locationHistoryPlay() {
        
        let sec:Double = Double(1.0 / speedSlider.value)
        
        timer = Timer.scheduledTimer(timeInterval: sec, target: self, selector: #selector(timerSelector), userInfo: nil, repeats: true)
        
        timer?.fire()
        
    }
    
    // MARK: - Timer selector
    func timerSelector() {
        
        print(index)
        
        
        if dataArray != nil {
            
            if (dataArray?.count)! > 0 {
                
                if index < (dataArray?.count)! {
                    
                    progressSlider.value = Float(index)
                    
                    let historyTrackPoiDataByTime = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[index])
                    
                    let coor:CLLocationCoordinate2D = CLLocationCoordinate2DMake((historyTrackPoiDataByTime?.Lat?.doubleValue)!, (historyTrackPoiDataByTime?.Lng?.doubleValue)!)
                    
                    drawShortLine()
                    
                    // MARK: 添加annotation
                    if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                        
                        baiduMapView?.removeAnnotations(baiduMapView?.annotations)
                        
                        
                        let coordinate = coorForWGS84ToBd09(coor: coor)
                        
                        let annotation = BMKPointAnnotation.init()
                        annotation.coordinate = coordinate
                        
                        
                        self.baiduMapView?.addAnnotation(annotation)
                        
                        self.baiduMapView?.setCenter(coordinate, animated: false)
                        
                        
                    }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                        
                        aMapView?.removeAnnotations(aMapView?.annotations)
                        
                        
                        
                        let coordinate = AMapCoordinateConvert(coor, .GPS)
                        
                        let annotation = MAPointAnnotation()
                        annotation.coordinate = coordinate
                        
                        
                        self.aMapView?.addAnnotation(annotation)
                        
                        setUpLHPlayViewControllerForAMap()
                        
                        self.aMapView?.selectAnnotation(annotation, animated: false)
                        
                        self.aMapView?.setCenter(coordinate, animated: false)
                        
                    }
                    
                    
                    index += 1
                    
                    
                    
                    
                }else {
                    
                    index = 0
                    
                    progressSlider.value = 0
                    
                    playButton.isSelected = false
                    
                    timer?.invalidate()
                    
                    let alertController = UIAlertController.init(title: NSLocalizedString(LOCALIZABLE_STRING_PLAY_FINISH, comment: ""), message: nil, preferredStyle: .alert)
                    
                    let confirmAction = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_CONFIRM, comment: ""), style: .cancel, handler: nil)
                    
                    alertController.addAction(confirmAction)
                    
                    self.present(alertController, animated: true, completion: nil)
                    
                }

                
            }
            
        }
        
        
        
        
    }
    
    // MARK: - 画短线
    func drawShortLine() {
        
        var coors:[CLLocationCoordinate2D] = []
        
        var pointArray:[CLLocationCoordinate2D] = []
        
        if index > 0 {

                
            let h1 = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[index - 1])
            
            let h2 = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[index])
                
            let c1 = CLLocationCoordinate2DMake((h1?.Lat?.doubleValue)!, (h1?.Lng?.doubleValue)!)
            
            let c2 = CLLocationCoordinate2DMake((h2?.Lat?.doubleValue)!, (h2?.Lng?.doubleValue)!)
                
            pointArray.append(c1)
            
            pointArray.append(c2)

            
        }else {
            
            if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
                
                baiduMapView?.removeOverlays(baiduMapView?.overlays)
                
            }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
                
                aMapView?.removeOverlays(aMapView?.overlays)

            }
            
            return
            
        }
        
        
        
        
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            for coor in pointArray {
                
                coors.append(self.coorForWGS84ToBd09(coor: coor ))
                
            }

            
            let polyline: BMKPolyline = BMKPolyline(coordinates: &coors, count: UInt(coors.count))
            
            self.baiduMapView?.add(polyline)
            
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            for coor in pointArray {
                
                coors.append(AMapCoordinateConvert(coor , .GPS))
                
            }
            
            let polyline: MAPolyline = MAPolyline(coordinates: &coors, count: UInt(coors.count))
            
            self.aMapView?.add(polyline)
            
            
        }

        
    }
    
    // MARK: - 画长线
    func drawLongLine() {
        
        var coors:[CLLocationCoordinate2D] = []
        
        var pointArray:[CLLocationCoordinate2D] = []
        
        if index > 0 {
            
            for i in 0...index {
                
                let h = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[i])
                
                let c = CLLocationCoordinate2DMake((h?.Lat?.doubleValue)!, (h?.Lng?.doubleValue)!)
                
                pointArray.append(c)
                
            }
            
            
        }else {
            
            return
            
        }
        
        
        
        
        
        if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_BAIDU_MAP {
            
            for coor in pointArray {
                
                coors.append(self.coorForWGS84ToBd09(coor: coor ))
                
            }
            
            
            
            
            // 大头针
            self.baiduMapView?.removeOverlays(self.baiduMapView?.overlays)
            
            
            
            let polyline: BMKPolyline = BMKPolyline(coordinates: &coors, count: UInt(coors.count))
            
            self.baiduMapView?.add(polyline)
            
            baiduMapView?.removeAnnotations(baiduMapView?.annotations)
            
            
            let coordinate = coorForWGS84ToBd09(coor: pointArray.last!)
            
            let annotation = BMKPointAnnotation.init()
            annotation.coordinate = coordinate
            
            self.baiduMapView?.addAnnotation(annotation)
            
            self.baiduMapView?.setCenter(coordinate, animated: false)
            
            
        }else if UserModel.userModel.selectedMap == LOCALIZABLE_STRING_AMAP {
            
            for coor in pointArray {
                
                coors.append(AMapCoordinateConvert(coor , .GPS))
                
            }
            
            
            
            self.aMapView?.removeOverlays(self.aMapView?.overlays)
            
            
            
            
            let polyline: MAPolyline = MAPolyline(coordinates: &coors, count: UInt(coors.count))
            
            self.aMapView?.add(polyline)
            
            
            // 大头针
            aMapView?.removeAnnotations(aMapView?.annotations)
            
            
            
            let coordinate = AMapCoordinateConvert(pointArray.last!, .GPS)
            
            let annotation = MAPointAnnotation()
            annotation.coordinate = coordinate
            
            
            self.aMapView?.addAnnotation(annotation)
            
            setUpLHPlayViewControllerForAMap()
            
            self.aMapView?.selectAnnotation(annotation, animated: false)
            
            self.aMapView?.setCenter(coordinate, animated: false)
            
            
        }
        
    }
    
    // MARK: - 获取气泡String
    func getTitleString() -> String {
        
        if dataArray != nil {
            
            if (dataArray?.count)! > 0 {
                
                let h = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[index])
                
                if h != nil {
                    
                    //serialNumber
                    let ser = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":" + (h?.SerialNumber)! + "\n"
                    
                    //time
                    let dateFormatter = DateFormatter.init()
                    dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
                    
                    let date = Date.init(timeIntervalSince1970: (h?.GPSTime?.doubleValue)!)
                    
                    let timeString = dateFormatter.string(from: date)
                    
                    let time = NSLocalizedString(LOCALIZABLE_STRING_TIME, comment: "") + ":" + timeString + "\n"
                    
                    //speed
                    let speed = NSLocalizedString(LOCALIZABLE_STRING_SPEED, comment: "") + ":" + (h?.Speed?.stringValue)! + "km/h"
                    
                    return (ser + time + speed)
                    
                }
                
            }
            
        }
        
        return (NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":\n" + NSLocalizedString(LOCALIZABLE_STRING_TIME, comment: "") + ":\n" + NSLocalizedString(LOCALIZABLE_STRING_SPEED, comment: "") + ":")
        
    }
    
    // MARK: - 初始化LHPlayViewControllerForAMap
    func setUpLHPlayViewControllerForAMap() {
        
        if dataArray != nil {
            
            if (dataArray?.count)! > 0 {
                
                let h = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[index])
                
                if h != nil {
                    
                    //serialNumber
                    let ser = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":" + (h?.SerialNumber)!
                    
                    //time
                    let dateFormatter = DateFormatter.init()
                    dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
                    
                    let date = Date.init(timeIntervalSince1970: (h?.GPSTime?.doubleValue)!)
                    
                    let timeString = dateFormatter.string(from: date)
                    
                    let time = NSLocalizedString(LOCALIZABLE_STRING_TIME, comment: "") + ":" + timeString
                    
                    //speed
                    let speed = NSLocalizedString(LOCALIZABLE_STRING_SPEED, comment: "") + ":" + (h?.Speed?.stringValue)! + "km/h"
                    
                    
                    lhplayViewControllerForAMap.serialNumber = ser
                    lhplayViewControllerForAMap.time = time
                    lhplayViewControllerForAMap.speed = speed
                    
                }
                
            }
            
        }
        
        
        
        
    }
    
    // MARK: - 设置百度annotationView
    func setUpBMKAnnotationView(annotationView:BMKCustomAnnotationView) {
        
        if dataArray != nil {
            
            if (dataArray?.count)! > 0 {
                
                let h = HistoryTrackPoiDataByTime.mj_object(withKeyValues: dataArray?[index])
                
                if h != nil {
                    
                    //serialNumber
                    let ser = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SERIAL_NUMBER, comment: "") + ":" + (h?.SerialNumber)!
                    
                    //time
                    let dateFormatter = DateFormatter.init()
                    dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
                    
                    let date = Date.init(timeIntervalSince1970: (h?.GPSTime?.doubleValue)!)
                    
                    let timeString = dateFormatter.string(from: date)
                    
                    let time = NSLocalizedString(LOCALIZABLE_STRING_TIME, comment: "") + ":" + timeString
                    
                    //speed
                    let speed = NSLocalizedString(LOCALIZABLE_STRING_SPEED, comment: "") + ":" + (h?.Speed?.stringValue)! + "km/h"
                    
                    
                    annotationView.serialNumber = ser
                    annotationView.time = time
                    annotationView.speed = speed
                    
                }
                
            }
            
        }
        
        
        
        
    }
    
    // MARK: - 返回AnnotationView  delegate
    func mapView(_ mapView: BMKMapView!, viewFor annotation: BMKAnnotation!) -> BMKAnnotationView! {
        
        if annotation.isKind(of: BMKPointAnnotation.classForCoder()) {
            
            let newAnnotaitonView = BMKCustomAnnotationView.init(annotation: annotation, reuseIdentifier: "myAnnotation")
            
            setUpBMKAnnotationView(annotationView: newAnnotaitonView!)
            
            newAnnotaitonView?.image = #imageLiteral(resourceName: "z_gps_realTime_GPS")
            
            newAnnotaitonView?.centerOffset = CGPoint.init(x: 0, y: -((newAnnotaitonView?.frame.size.height)! / 2))
            
            newAnnotaitonView?.setSelected(true, animated: false)
            
            return newAnnotaitonView
            
        }
        
        return nil
        
    }
    
    // MARK: - 转换百度坐标
    func coorForWGS84ToBd09(coor:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        
        //转换WGS84坐标至百度坐标(加密后的坐标)
        let testdic = BMKConvertBaiduCoorFrom(coor, BMK_COORDTYPE_GPS)
        
//        print(testdic!)
        
        //解密加密后的坐标字典
        let baiduCoor = BMKCoorDictionaryDecode(testdic)//转换后的百度坐标
        
        return baiduCoor
        
    }
    
    // MARK: - 画线代理
    func mapView(_ mapView: BMKMapView!, viewFor overlay: BMKOverlay!) -> BMKOverlayView! {
        
        if overlay.isKind(of: BMKPolyline.self) {
            
            let polylineView = BMKPolylineView(overlay: overlay)
            
            polylineView?.strokeColor = UIColor.blue
            
            polylineView?.lineWidth = 2.0
            
            
            
            return polylineView
            
        }
        
        return nil
        
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class LHPlayViewControllerForAMap: NSObject,MAMapViewDelegate {
    
    var serialNumber:String?
    var time:String?
    var speed:String?
    
    // MARK: - annotationView代理
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation.isKind(of: MAPointAnnotation.classForCoder()) {
            
            let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation")
            var newAnnotaitonView:CustomAnnotationView
            if (annotationView == nil)
            {
                newAnnotaitonView = CustomAnnotationView.init(annotation: annotation, reuseIdentifier: "myAnnotation")
                
            }else {
                
                newAnnotaitonView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as! CustomAnnotationView
                
            }
            
            newAnnotaitonView.serialNumber = serialNumber
            
            newAnnotaitonView.time = time
            
            newAnnotaitonView.speed = speed
            
            
            
            
            newAnnotaitonView.image = #imageLiteral(resourceName: "z_gps_realTime_GPS")
            
            newAnnotaitonView.centerOffset = CGPoint.init(x: 0, y: -((newAnnotaitonView.frame.size.height) / 2))
            
//            newAnnotaitonView.canShowCallout = true
            
            
            
            return newAnnotaitonView
            
        }
        
        return nil
        
    }
    
    
    // MARK: - 画线代理
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        if overlay.isKind(of: MAPolyline.self) {
            
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: overlay)
            
            renderer.lineWidth = 5.0
            
            renderer.strokeColor = UIColor.blue
            
            return renderer
        }
        return nil
    }
    
}
